package com.mysteel.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.mysteel.common.to.es.SkuEsModel;
import com.mysteel.search.config.ElasticSearchConfig;
import com.mysteel.search.constant.EsConstant;
import com.mysteel.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ProjectName: mail
 * ClassName: ProductSaveServiceImpl
 * Description:
 * date: 2021/01/23/023 10:21
 *
 * @author xiaochao
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 建立索引及映射关系

        // 批量保存数据至ES
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String jsonString = JSON.toJSONString(model);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // todo 如果有错误，需处理
        boolean hasFailures = bulk.hasFailures();
        if (hasFailures){
            log.error("商品上架出现异常：{}",Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList()));
        }
        return hasFailures;
    }
}
